package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.RegisterAddressBean;
import com.hd.crdao.bean.RegisterInfoBean;
import com.hd.crdao.bean.SmsCheckInfoBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.CheckUtils;
import com.hd.crdao.utils.MobileDesUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.TimeDownCounter;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/5/24 0024
 */
public class RegisterActivity extends BaseSecondActivity {

    public TimeDownCounter mTimeDownCounter;
    @BindView(R.id.register_head)
    ExpandHeadView mRegisterHead;
    @BindView(R.id.telephone)
    EditText mTelephone;
    @BindView(R.id.getcheckcode)
    Button mGetcheckcode;
    @BindView(R.id.checkcode)
    EditText mCheckcode;
    @BindView(R.id.realName)
    EditText mRealName;
    @BindView(R.id.password)
    EditText mPassword;
    @BindView(R.id.comfirmpwd)
    EditText mComfirmpwd;
    /*@BindView(R.id.cbContact)
    EditText mCbContact;*/
    @BindView(R.id.companyname)
    EditText mCompanyname;
    @BindView(R.id.provincecity)
    TextView mProvincecity;
    @BindView(R.id.select_city)
    LinearLayout mSelectCity;
    @BindView(R.id.detailaddress)
    EditText mDetailaddress;
    @BindView(R.id.checkBox)
    CheckBox mCheckBox;
    @BindView(R.id.serviceagreement)
    TextView mServiceagreement;
    @BindView(R.id.agreetoregister)
    Button mAgreetoregister;
    private String areaId;

    /**
     * 表示已经发送了短信
     */
    public boolean hasSendMsg;
    public GeoCoder geoCoder;


    @Override
    protected int setContentView() {
        return R.layout.activity_register;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mRegisterHead;
    }

    @Override
    protected void initView() {
        // Spanned spanned = Html.fromHtml("<font color='red'>同意服务协议</font>");
        //设置服务条款协议的富文本
        SpannableString spannableString = new SpannableString("《同意服务协议》");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
        spannableString.setSpan(colorSpan, 1, spannableString.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mServiceagreement.setText(spannableString);
        mCheckBox.setChecked(true);
        EventBus.getDefault().register(this);

     /*   mDetailaddress.addTextChangedListener(new SimpleTextChangeWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                super.afterTextChanged(editable);
                String address = mDetailaddress.getText().toString().trim();
                address = address + mProvincecity.getText().toString().trim();
                getLocation(address);

            }
        });*/


    }


    /**
     * 获取验证码操作,先对手机号码进行校验,如果通过了校验才会去获取验证码
     */
    private void getCheckCode() {
        String phoneNumber = mTelephone.getText().toString().trim();
        if (CheckThePhoneNumber(phoneNumber)) {
            getCheckCode(phoneNumber);
            hasSendMsg = true;
        }

    }

    /**
     * 检验手机号码
     */
    private boolean CheckThePhoneNumber(String phoneNumber) {
        if (TextUtils.isEmpty(phoneNumber)) {
            MyToast.show("手机号码不能为空");
            return false;
        } else if (phoneNumber.length() == 11 && CheckUtils.isMobileNO(phoneNumber)) {
            return true;
        } else {
            MyToast.show("手机号码不合法");
            return false;
        }
    }


    /**
     * 该方法用于获得验证码
     *
     * @param phoneNumber
     */
    public void getCheckCode(String phoneNumber) {
        OkHttpUtils.post().url(Constants.GETSMSCODE_URL)
                .addParams("mobile", phoneNumber)
                .addParams("smsType", "1")  //注册
                .addParams("sign", Constants.SIGN)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("服务器连接失败或异常");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                Gson gson = new Gson();
                SmsCheckInfoBean smsCheckInfoBean = gson.fromJson(response, SmsCheckInfoBean.class);
                if (smsCheckInfoBean.getSuccess() == 0) {
                    MyToast.show(smsCheckInfoBean.getMessage());
                    mTimeDownCounter = new TimeDownCounter(60000, 1000, mGetcheckcode);
                    mTimeDownCounter.start();
                } else {
                    MyToast.show(smsCheckInfoBean.getMessage());
                }
            }
        });
    }

    /**
     * 注册操作
     * 1.首先需要判断手机号码和验证码是否为空,
     */
    private void doRegister() {
        String telephone = mTelephone.getText().toString().trim();          //电话号码
        String checkCode = mCheckcode.getText().toString().trim();      //验证码
        if (!CheckThePhoneNumber(telephone)) {
            return;
        }
        if (TextUtils.isEmpty(telephone)) {
            MyToast.show("请填写手机号码");
            return;
        }
        if (TextUtils.isEmpty(checkCode)) {
            MyToast.show("请填写验证码");
            return;
        }
        String realName = mRealName.getText().toString().trim();//会员登录名
        String password = mPassword.getText().toString().trim();    //密码
        String confirmPwd = mComfirmpwd.getText().toString().trim();//确认密码
        //  String recomMobile = mCbContact.getText().toString().trim();
        String companyName = mCompanyname.getText().toString().trim();//公司名字
        String detailAddress = mDetailaddress.getText().toString().trim();//详细情况
        if (TextUtils.isEmpty(telephone) || TextUtils.isEmpty(realName) || TextUtils.isEmpty(password)
                || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPwd)
                || TextUtils.isEmpty(detailAddress)
                ) {
            MyToast.show("请填写完整注册信息");
            return;
        } else if (!TextUtils.equals(password, confirmPwd)) {
            MyToast.show("两次密码不一致");
            return;
        }
        //密码校验OK之后 选择城市,详细地址和服务协议
        String provincecity = mProvincecity.getText().toString().trim();
        if (TextUtils.equals(provincecity, "点击选择城市")) {
            MyToast.show("请选择城市");
            return;
        }
        String encPassword = MobileDesUtils.strEnc(password, Constants.FIRSTKEY, null, null);
        // String address = provincecity + detailAddress;
        if (TextUtils.isEmpty(detailAddress)) {
            MyToast.show("请输入详细地址");
            return;
        }
        getLocation(provincecity, detailAddress, telephone, checkCode,
                realName, encPassword,
                "", companyName,
                detailAddress);


    }


    /**
     * 上传注册信息给服务器
     *
     * @param telephone
     * @param checkCode
     * @param realName
     * @param encPassword
     * @param recomMobile
     * @param companyName
     * @param address
     * @param cbxy
     */
    private void getRegisterInfo(String telephone, String checkCode,
                                 String realName, final String encPassword,
                                 String recomMobile, String companyName,
                                 String address, String cbxy) {

        if (!mCheckBox.isChecked()) {
            MyToast.show("同意服务协议才能注册哦!");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("sign", Constants.SIGN);
        map.put("appFlag", "true");
        map.put("loginName", telephone);
        map.put("loginPwd", encPassword);
        map.put("mobile", telephone);
        map.put("companyName", companyName);
        map.put("areaId", areaId);
        map.put("address", address);
        map.put("cbxy", cbxy);
        ALog.d("放进集合中的值CBXY:" + cbxy);
        if (!TextUtils.isEmpty(recomMobile)) {
            map.put("recomMobile", recomMobile);
        }
        map.put("cbContacts", realName);
        if (!TextUtils.isEmpty(checkCode)) {
            map.put("smsCode", checkCode);
        }
        map.put("smsType", "1");
        try {
            OkHttpUtils.post().url(Constants.REGISTER_URL).params(map).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    MyToast.show("服务器连接异常或失败");
                }

                @Override
                public void onResponse(String response, int id) {
                    ALog.d(response);
                    RegisterInfoBean registerInfoBean = new Gson().fromJson(response, RegisterInfoBean.class);
                    if (registerInfoBean.getSuccess() == 0) {
                        MyToast.show(registerInfoBean.getMessage());
                        Intent intent = new Intent(UIUtils.getContext(), LoginActivity.class);
                        intent.putExtra("loginName", registerInfoBean.getCarBusiness().getUser().getLoginName());
                        intent.putExtra("password", mComfirmpwd.getText().toString().trim());
                        startActivity(intent);
                        finish();
                    } else {
                        MyToast.show(registerInfoBean.getMessage());
                        return;
                    }

                }
            });
        } catch (Exception e) {
            ALog.d(e.getMessage());
        }
    }


    /**
     * 检查所输入地址是否匹配
     *
     * @param provincecity
     * @param detailAddress
     * @param telephone
     * @param checkCode
     * @param realName
     * @param encPassword
     * @param recomMobile
     * @param companyName
     * @param address
     */
    private void getLocation(String provincecity, String detailAddress, final String telephone, final String checkCode, final String realName, final String encPassword, final String recomMobile, final String companyName, final String address) {
        geoCoder = GeoCoder.newInstance();
        GeoCodeOption geoCodeOption = new GeoCodeOption();
        geoCodeOption.city(provincecity);
        geoCodeOption.address(detailAddress);
        geoCoder.geocode(geoCodeOption);
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                if (geoCodeResult == null || geoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    MyToast.show("您输入的地址有错误,请检查后输入!");
                } else {
                    LatLng location = geoCodeResult.getLocation();
                    String cbxy = location.latitude + "," + location.longitude;
                    ALog.d(cbxy);
                    ALog.d("获取位置的方法已经执行");

                    getRegisterInfo(telephone, checkCode, realName, encPassword, recomMobile, companyName, address, cbxy);
                }
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

            }

        });


    }


    /**
     * 弹出服务协议
     */
    private void showServiceAgreement() {
        Intent intent = new Intent(UIUtils.getContext(), LoadUrlAboutUsActivity.class);
        intent.putExtra("url", "serviceAgreement");
        startActivity(intent);
    }

    /**
     * 选择城市
     */
    private void selectCity() {
        Intent intent = new Intent(UIUtils.getContext(), AddressActivity.class);
        intent.putExtra("fromWhere", "register");
        startActivity(intent);
    }


    @OnClick({R.id.getcheckcode, R.id.select_city, R.id.checkBox, R.id.serviceagreement, R.id.agreetoregister})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.getcheckcode:
                getCheckCode(); //获取验证码
                break;
            case R.id.select_city:
                selectCity();       //选择城市
                break;
           /* case R.id.checkBox:
                if (mCheckBox.isChecked()) {
                    mAgreeregister.setEnabled(true);

                } else {
                    mAgreeregister.setEnabled(false);
                }
                break;*/
            case R.id.serviceagreement:
                showServiceAgreement(); //显示服务协议
                break;
            case R.id.agreetoregister:
                //在注册之后需要进行健壮性判断
                doRegister();
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getAddress(RegisterAddressBean registerAddressBean) {
        String addressinfo = registerAddressBean.getProvinceName() + " " + registerAddressBean.getCityName()
                + " " + registerAddressBean.getAreaName();
        mProvincecity.setText(addressinfo);
        areaId = registerAddressBean.getAreaid();
        ALog.d(areaId + "+++++++++++++地区的id哈哈哈哈哈哈");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mTimeDownCounter != null) {
            mTimeDownCounter.cancel();
            mTimeDownCounter = null;
        }
        if (geoCoder != null) {
            geoCoder.destroy();
        }
    }

}
